#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UITextField.h>
#import <UIKit/UITextLabel.h>
#import <UIKit/UITextView.h>
#import <UIKit/UIKeyboard.h>
#import <UIKit/UINavigationBar.h>
#import <UIKit/UIWindow.h>
#import <UIKit/UIView-Hierarchy.h>
#import <UIKit/UIHardware.h>
#import <UIKit/UITable.h>
#import <UIKit/UITableCell.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UITouchDiagnosticsLayer.h>
#import <UIKit/UIFontChooser.h>
#import "MobileToDoListApplication.h"


static MobileToDoListApplication *sharedInstance;

@implementation MobileToDoListApplication

+ (MobileToDoListApplication *)sharedInstance
{
	if (!sharedInstance)
		sharedInstance = [[MobileToDoListApplication alloc] init];
	
	return sharedInstance;
}

- (void) applicationWillTerminate {
	[self updateBadge];
}

- (void) applicationResume:(struct __GSEvent *) event {
	[self updateBadge];
}

- (void) applicationSuspend:(struct __GSEvent *) event {
	[self updateBadge];
	[self terminateWithSuccess];
}

- (void)updateBadge
{
	if([toDoManager numberOfOpenTodos]){
		[self setApplicationBadge: [NSString stringWithFormat: @"%d", [toDoManager numberOfOpenTodos]]];
	}
	else {
		[self setApplicationBadge: @""];
	}
}

- (void) applicationDidFinishLaunching: (id) unused
{
	// init the singleton
	sharedInstance = self;
	
	// sconfiguration
	dirPath = @"/var/root/Library/MobileToDoList";
	filePath = @"/var/root/Library/MobileToDoList/todos.dat";
	groupFilePath = @"/var/root/Library/MobileToDoList/groups.dat";
	preferenceFilePath = @"/var/root/Library/MobileToDoList/preferences.dat";
	
	//Check to see if directory exists
	if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath])
	{
		[[NSFileManager defaultManager] createDirectoryAtPath:dirPath attributes:nil];
	}
	
	
	
	
	toDoManager = [ToDoManager sharedToDoManager];
	[toDoManager setCurrentFile:filePath];
	[toDoManager setCurrentGroupFile:groupFilePath];
	[toDoManager setCurrentPreferenceFile:preferenceFilePath];

	[toDoManager loadPreferences];
	[toDoManager loadFile];
	[toDoManager deleteAllOldToDos];
	[toDoManager orderTodosByGroup];
	
	//[self loadURL];
	
  mainWindow = [[UIWindow alloc] initWithContentRect: [UIHardware
						    fullScreenApplicationContentRect]];

	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
  rect.origin.x = rect.origin.y = 0.0f;

	transitionView = [[UITransitionView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	
  mainView = [[UIView alloc] initWithFrame: rect];



	[mainView addSubview:transitionView];

	mainWindow = [[UIWindow alloc] initWithContentRect:rect];
	[mainWindow setContentView:mainView];



	[mainWindow orderFront:self];
	[mainWindow makeKey:self];
	[mainWindow _setHidden:NO];
	
	if (!toDoView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoView = [[ToDoView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	
	
	
	betaInfoSheet = [ [ UIAlertSheet alloc ] initWithFrame:
      CGRectMake(0, 240, 320, 240) ];
  [ betaInfoSheet setTitle:@" ==[ Version 0.4 ]== " ];
  [ betaInfoSheet setBodyText:@"This application isn't finished right now!\n\n\ninfos: www.include7.ch/mobiletodolist\n\nhelp developing this app, please donate.\n\nsend whishes and bugs to: iphone@include7.ch\n\ndeveloped by unas" ];
  [ betaInfoSheet addButtonWithTitle:@"OK" ];
  [ betaInfoSheet setDelegate: self ];
  
	
	changesSheet = [ [ UIAlertSheet alloc ] initWithFrame:
      CGRectMake(0, 240, 320, 240) ];
  [ changesSheet setTitle:@" ==[ changes to 0.3 ]== " ];
  [ changesSheet setBodyText:@"+ auto-delete todos after x days\n+ show priority icon in table\n+ set order by method" ];
  [ changesSheet addButtonWithTitle:@"OK" ];
  [ changesSheet setDelegate: self ];
	
	nextFuturesSheet = [ [ UIAlertSheet alloc ] initWithFrame:
      CGRectMake(0, 240, 320, 240) ];
  [ nextFuturesSheet setTitle:@" ==[ next functions ]== " ];
  [ nextFuturesSheet setBodyText:@"+ complete recode\n+ notes\n+ websync " ];
  [ nextFuturesSheet addButtonWithTitle:@"OK" ];
  [ nextFuturesSheet setDelegate: self ];

	//[transitionView transition:1 toView:toDoDetailView];
	[self showToDosWithTransition:1];
}

- (void)showBetaSheet
{
	[ betaInfoSheet presentSheetInView: mainView ];
}

- (void)showChangesSheet
{
	[ changesSheet presentSheetInView: mainView ];
}
- (void)showNextFuturesSheet
{
	[ nextFuturesSheet presentSheetInView: mainView ];
}
- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
    [ sheet dismiss ];
}

- (void)showToDosWithTransition:(int)trans
{
	if (!toDoView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoView = [[ToDoView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoManager orderTodosByGroup];
	[toDoView reloadTableData];
	[transitionView transition:trans toView:toDoView];
}

- (void)showToDoDetailsWithTransition:(int)trans
{
	if (!toDoDetailView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoDetailView = [[ToDoDetailView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoDetailView reloadTableData];
	[transitionView transition:trans toView:toDoDetailView];
}

- (void)showToDoGroupsWithTransition:(int)trans
{
	if (!toDoGroupView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoGroupView = [[ToDoGroupView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoGroupView reloadTableData];
	[transitionView transition:trans toView:toDoGroupView];
}

- (void)showToDoOrderByWithTransition:(int)trans
{
	if (!toDoOrderByView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoOrderByView = [[ToDoOrderByView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoOrderByView reloadTableData];
	[transitionView transition:trans toView:toDoOrderByView];
}

- (void)showToDoDeleteAfterWithTransition:(int)trans
{
	if (!toDoDeleteAfterView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoDeleteAfterView = [[ToDoDeleteAfterView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoDeleteAfterView reloadTableData];
	[transitionView transition:trans toView:toDoDeleteAfterView];
}


- (void)showToDoSetDateWithTransition:(int)trans forDate:(int)date
{
	if (!toDoSetDateView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoSetDateView = [[ToDoSetDateView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoSetDateView setDateType:date];
	[toDoSetDateView reloadTableData];
	[transitionView transition:trans toView:toDoSetDateView];
}

- (void)showToDoPreferencesWithTransition:(int)trans
{
	if (!toDoPreferenceView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoPreferenceView = [[ToDoPreferenceView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	
	[transitionView transition:trans toView:toDoPreferenceView];
}

- (void)showToDoGroupsEditWithTransition:(int)trans
{
	if (!toDoGroupEditView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoGroupEditView = [[ToDoGroupEditView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	
	[toDoGroupEditView reloadTableData];
	[transitionView transition:trans toView:toDoGroupEditView];
}

- (void)showToDoGroupDetailWithTransition:(int)trans
{
	if (!toDoGroupDetailView)
	{
		struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
		rect.origin.x = rect.origin.y = 0.0f;
		
		toDoGroupDetailView = [[ToDoGroupDetailView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	}
	[toDoGroupDetailView reloadTableData];
	[transitionView transition:trans toView:toDoGroupDetailView];
}

- (void)applicationWillSuspend
{
	[toDoManager writeToFile];
}

- (void)loadURL
{
		//LOAD A FILE
		NSURLResponse *response=0;
		NSError *error=0;
		NSData *myData;

		NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://jschnelli:CaleSujo34@sys.include7.ch/calendars/ARTACK.ics"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];

		myData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &response error: &error];
	//	NSError *err = nil;

		/* NOTE: This way of doing NSXMLDocument is to work around a problem with the
		ARM linker. For some reason, it does not see the NSXMLDocument symbol that is defined
		in the OfficeImport framework. So we resolve the symbol at runtime. */
		//xmlDoc = [[[NSClassFromString(@"NSXMLDocument") alloc] initWithData:myData options:NSXMLNodeOptionsNone error:&err] autorelease];
		NSString *stringFromASC = [NSString stringWithCString:[myData bytes] length:[myData length]];
		NSArray *lines=[stringFromASC componentsSeparatedByString:@"\n"];
		int i;
		BOOL inToDo;
		inToDo = NO;
		for(i=0;i < [lines count]-1;i++) {
			NSString *myText = [[lines objectAtIndex:i] substringToIndex:([[lines objectAtIndex:i] length]-1)];
			// UTF8 Parsing!
			if([myText isEqualToString:@"BEGIN:VTODO"]) {
				inToDo = YES;
			}
			if([myText isEqualToString:@"END:VTODO"]) {
				inToDo = NO;
			}
			if(inToDo) {
				if([myText length] >6) {
					if([[myText substringToIndex:7] isEqualToString:@"SUMMARY"]) {
						
						// FOUND A TODO:
						int num;
						ToDo *myToDo = [[ToDo alloc] init];
						num = [toDoManager addToDo:myToDo];
						[toDoManager setDescription:[myText substringFromIndex:8] forToDo:num-1];
					}				
				}
			}
		}
}
@end
